package es

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/olivere/elastic/v7"
	"zg6/zg6_month/goodssrv/goodssrv"
	"zg6/zg6_month/goodssrv/model"
)

func SearchGoods(query elastic.Query, high *elastic.Highlight, page int) ([]*goodssrv.Goods, error) {
	var (
		size   = 3
		esMaps []map[string]interface{}
		list   []*goodssrv.Goods
	)
	if page == 1 {
		page = 1
	}
	count, _ := model.EsClient.Count().Index(model.ES_INDEX).Query(query).Do(context.Background())
	limit := int64(page-1) * count
	res, err := model.EsClient.Search().Index(model.ES_INDEX).Query(query).Highlight(high).From(int(limit)).Size(size).Sort("GoodsPrice", false).Do(context.Background())
	if err != nil {
		return nil, err
	}
	for _, hit := range res.Hits.Hits {
		var esMap map[string]interface{}
		json.Unmarshal(hit.Source, &esMap)
		for i, s := range hit.Highlight {
			esMap[i] = s[0]
		}
		esMaps = append(esMaps, esMap)
	}
	fmt.Println(esMaps, "]]]]")
	for _, v := range esMaps {
		list = append(list, &goodssrv.Goods{
			Id:         int32(v["ID"].(float64)),
			GoodsName:  v["GoodsName"].(string),
			GoodsSn:    v["GoodsSn"].(string),
			ClickNum:   int32(v["ClickNum"].(float64)),
			SoldNum:    int32(v["SoldNum"].(float64)),
			ShopPrice:  float32(v["ShopPrice"].(float64)),
			GoodsStock: int32(v["GoodsStock"].(float64)),
			GoodsDesc:  v["GoodsDesc"].(string),
			Status:     int32(v["Status"].(float64)),
		})
	}
	return list, nil
}
